import React, { useState, useEffect } from "react";
import Note from "./Note";
import Editor from "./Editor";
import { db, loadCollection } from '../database'
import { Collection } from "lokijs";

const Notes = () => {
    // MVVM
    const [notes, setNotes] = useState([])
    const destroyEntity = (entity) => {
        // 不是所选项的留下给setState filter
        const _entities = notes.filter(
            item => item.$loki !== entity.$loki
        )
        console.log('delete' + entity)
        setNotes(_entities)
        // 同步到数据库中
        loadCollection('notes')
            .then((collection) => {
                collection.remove(entity)
                db.saveDatabase()
            })

    }
    const createEntity = () => {

    }

    const noteItems = notes.map( // JSX 一次性输出Note
        (note) =>
            <Note
                key={note.$loki}// 唯一键
                entity={note}// 实体
                destroyEntity={destroyEntity}
            />
    )
    const getInitialData = () => {
        loadCollection('notes')
            .then((collection) => {
                // console.log(collection);
                // collection.insert([
                //     { body: "hello" }
                // ])
                const entities = collection.chain()
                    .find() // select * from orderby
                    .simplesort('$loki', 'isdesc') // 排序 desc 降序
                    .data()
                console.log(entities)
                setNotes(entities)
            })
    }

    // 先把页面模板显示出来 静态部分先显示出来 保证渲染顺序
    // JSX -》babel + html / css 组件挂载及渲染时间 静态
    // 从数据库里去取 useEffect DOMContentLoaded 动态 
    // useEffect 在组件挂载后执行 生命周期
    // setNotes 列表出来
    useEffect(() => {
        getInitialData() // 数据库
    }, [])

    return (
        <div className="ui container notes">
            <h4 className="ui horizontal divider header">
                <i className="paw icon" />
                Notes App _ React.js
            </h4>
            <button
                onClick={createEntity}
                className="ui right floated basic violet button">
                添加笔记
            </button>
            <div className="ui divided items">
                {noteItems}
                {/* JSX 一次性输出Note */}
            </div>
        </div>
    )
}

export default Notes;